package com.huang.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huang.entity.Menu;
import com.huang.mapper.MenuDao;
import com.huang.service.MenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author han
 * @since 2021-10-14 11:05:07
 */
@Service
@Transactional
public class MenuServiceImpl extends ServiceImpl<MenuDao, Menu> implements MenuService {

    @Resource
    private MenuDao menuDao;

    @Override
    public List<Menu> findByRoleIds(List<String> roleIds) {
        List<Menu> menus = menuDao.findByRoleIds(roleIds);
        List<Menu> collect = menus.stream().distinct().collect(Collectors.toList());
        List<Menu> selectMenus = collect.stream().filter(menu -> menu.getPid().equals("0")).collect(Collectors.toList());
        return getTreeMenus(collect, selectMenus);
    }

    /**
     * 获取树形结构的菜单
     *
     * @param menus         权限内的菜单
     * @param selectMenus   一级菜单
     */
    private List<Menu> getTreeMenus(List<Menu> menus, List<Menu> selectMenus) {
        if (null == selectMenus || selectMenus.size() <= 0) {
            return null;
        }
        for (Menu selectMenu : selectMenus) {
            List<Menu> childrenList = new ArrayList<>();
            for (Menu menu : menus) {
                if (selectMenu.getId().equals(menu.getPid())) {
                    childrenList.add(menu);
                }
            }
            selectMenu.setChildrenList(childrenList);
            getTreeMenus(menus, childrenList);
        }
        return selectMenus;
    }
}
